package logic

import (
	"context"
	"fmt"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
	"time"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/sn"
	"xialou_platform/services/agent/rpc/agentClient"
	v3 "xialou_platform/services/order/api/internal/wxpay/v3"
	"xialou_platform/services/order/rpc/orderClient"

	"xialou_platform/services/order/api/internal/svc"
	"xialou_platform/services/order/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderCreateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) OrderCreateLogic {
	return OrderCreateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderCreateLogic) OrderCreate(req *types.OrderCreateReq) (resp *types.OrderCreateResp, err error) {
	uid, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return nil, err
	}

	agentParam, err := l.svcCtx.AgentRpc.AgentById(l.ctx, &agentClient.IdBody{Id: uid})
	if err != nil {
		return nil, err
	}

	var money int64 = 0
	switch req.Type {
	case 1:
		// 代理商认证费用
		if agentParam.Status > 0 {
			switch agentParam.Type {
			case 1:
				money = 100000
				break
			case 2:
				money = 1000000
				break
			case 3:
				money = 10000000
				break
			}
		}

	default:
		return nil, errorx.NewDefaultError("你选择的业务不存在")
	}

	// 新增一条订单记录
	orderParam := &orderClient.OrderParam{
		Uid:       uid,
		Type:      1,
		SourceId:  agentParam.Type,
		Money:     money,
		OrderNum:  sn.GenSn(sn.SN_PREFIX_ORDER),
		PayType:   1,       // 微信支付
		TradeType: "JSAPI", // 小程序支付
		Remark:    "下楼销氪认证服务费",
	}
	_, err = l.svcCtx.OrderRpc.OrderAdd(l.ctx, orderParam)
	if err != nil {
		return nil, err
	}

	wxPayClient, err := v3.NewWxPayClientV3(l.svcCtx.Config.WxPayConf)
	if err != nil {
		return nil, err
	}
	jsApiSvc := jsapi.JsapiApiService{
		Client: wxPayClient,
	}

	paymentRes, _, err := jsApiSvc.PrepayWithRequestPayment(l.ctx,
		jsapi.PrepayRequest{
			Appid:       core.String(l.svcCtx.Config.WxPayConf.AppId),
			Mchid:       core.String(l.svcCtx.Config.WxPayConf.MchId),
			Description: core.String(orderParam.Remark),
			OutTradeNo:  core.String(orderParam.OrderNum),
			TimeExpire:  core.Time(time.Now().Add(time.Minute * 15)),
			Attach:      core.String(orderParam.Remark),
			NotifyUrl:   core.String(l.svcCtx.Config.WxPayConf.NotifyUrl),
			Amount: &jsapi.Amount{
				Total: core.Int64(orderParam.Money),
			},
			Payer: &jsapi.Payer{Openid: core.String(agentParam.OpenId)},
		})

	if err != nil {
		return nil, errorx.NewReasonError("生成微信支付预订单失败", fmt.Sprintf("err: %s, userId: %v, orderSn: %s", err.Error(), uid, orderParam.OrderNum))
	}

	resp = &types.OrderCreateResp{
		AppId:     *paymentRes.Appid,
		NonceStr:  *paymentRes.NonceStr,
		Package:   *paymentRes.Package,
		SignType:  *paymentRes.SignType,
		Timestamp: *paymentRes.TimeStamp,
		PaySign:   *paymentRes.PaySign,
	}

	return resp, nil
}
